package com.ahmedmisbah.andgenplus.codegenerator.parser;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.DocumentException;
import org.dom4j.Element;

import com.ahmedmisbah.andgenplus.codegenerator.beans.GeneratorDescriptor;
import com.ahmedmisbah.andgenplus.codegenerator.beans.GeneratorTemplate;
import com.ahmedmisbah.andgenplus.utils.xml.XMLUtil;

public class CodeGeneratorXMLParser extends XMLUtil {

	private final String ANDGENPLUS_NAME_TAG = "name";
	private final String ANDGENPLUS_CLASS_TAG = "class";
	private final String ANDGENPLUS_TEMPLATES_TAG = "templates";
	private final String ANDGENPLUS_TEMPLATE_NAME_ATTRIBUTE = "name";
	private final String ANDGENPLUS_TEMPLATE_TAG = "template";

	private Map<String, GeneratorTemplate> getTemplates(Element templatesElement) {

		Map<String, GeneratorTemplate> ret = new HashMap<String, GeneratorTemplate>();

		List<Element> templatesElementList = getElements(templatesElement);

		for (Element element : templatesElementList) {

			String tagName = element.getName();
			String tagValue = element.getTextTrim();

			GeneratorTemplate template = new GeneratorTemplate();

			if (tagName.equals(ANDGENPLUS_TEMPLATE_TAG)) {
				template.setTemplatePath(tagValue);
				String name = getAttribute(element,
						ANDGENPLUS_TEMPLATE_NAME_ATTRIBUTE);
				ret.put(name, template);
			}

		}

		return ret;
	}

	/**
	 * @param xmlPath
	 * @throws IOException
	 * @throws DocumentException
	 */
	public GeneratorDescriptor parseCodeGeneratorXML(String xmlPath)
			throws IOException, DocumentException {

		GeneratorDescriptor ret = new GeneratorDescriptor();

		Element root = load(xmlPath);
		List<Element> generator = getElements(root);

		for (Element element : generator) {

			String tagName = element.getName();
			String tagValue = element.getTextTrim();

			if (tagName.equals(ANDGENPLUS_NAME_TAG)) {
				ret.setName(tagValue);
			} else if (tagName.equals(ANDGENPLUS_CLASS_TAG)) {
				ret.setClassPath(tagValue);

			} else if (tagName.equals(ANDGENPLUS_TEMPLATES_TAG)) {
				Map<String, GeneratorTemplate> templateList = getTemplates(element);
				ret.setTemplates(templateList);

			}
		}

		return ret;
	}

}
